﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

using ILRuntime.Runtime.Enviorment;

public class ScriptMgr : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    public void LoadScript(AppDomain appdomain, string filename, System.Action<bool, string> callback = null)
    {
        this.StartCoroutine(_doLoading(appdomain, filename, callback));
    }

    IEnumerator _doLoading(AppDomain appdomain, string filename, System.Action<bool, string> callback)
    {
#if UNITY_ANDROID
        WWW www = new WWW(Application.streamingAssetsPath + "/ScriptProject.dll");
#else
        WWW www = new WWW("file://" + Application.streamingAssetsPath + "/" + filename);
#endif

        yield return www;

        if (!string.IsNullOrEmpty(www.error))
        {
            if (callback != null) callback(true, www.error);
        }

        byte[] dllBytes = www.bytes;
        www.Dispose();

#if UNITY_ANDROID
        www = new WWW(Application.streamingAssetsPath + "/ScriptProject.pdb");
#else
        www = new WWW("file://" + Application.streamingAssetsPath + "/ScriptProject.pdb");
#endif
        yield return www;

        if (!string.IsNullOrEmpty(www.error)) UnityEngine.Debug.LogError(www.error);

        byte[] pdb = www.bytes;
        using (System.IO.MemoryStream fs = new MemoryStream(dllBytes))
        {
            using (System.IO.MemoryStream p = new MemoryStream(pdb))
            {
                appdomain.LoadAssembly(fs, p, new Mono.Cecil.Pdb.PdbReaderProvider());
                //appdomain.LoadAssembly(fs);
            }
        }

        if(callback != null) callback(true, null);
    }

}
